package service

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"holidayone/basic/config"
	"holidayone/handler/model"
	"log"
	"strconv"
)

var (
	upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}
	Clients = map[string]*Node{}
)

type Node struct {
	UserId string
	conn   *websocket.Conn
	Data   chan []byte
}

func Chat(c *gin.Context) {
	userId := c.Query("userId")
	friendId := c.Query("friendId")

	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println(err)
		return
	}
	Clients[userId] = &Node{
		UserId: userId,
		conn:   conn,
		Data:   make(chan []byte, 100),
	}
	go func() {
		rab := NewRabbitMQSimple(userId)
		rab.Destory()
		rab.ConsumeSimple(Clients[userId])
	}()
	go RedMSg(Clients[userId], friendId)
	go SendSmsNode(Clients[userId])
}

func RedMSg(myNode *Node, friendId string) {
	UserId, _ := strconv.Atoi(myNode.UserId)
	FriendId, _ := strconv.Atoi(friendId)
	//var friend model.Friend
	//err := friend.IsFriend(config.DB, UserId, FriendId)
	//if err != nil {
	//	log.Println("好友关系不存在")
	//	return
	//}
	//var black model.Blacklist
	//err = black.IsBlacklist(config.DB, UserId, FriendId)
	//if err == nil {
	//	log.Println("黑名单好友存在")
	//	return
	//}
	rab := NewRabbitMQSimple(friendId)
	rab.Destory()

	for {
		_, data, err := myNode.conn.ReadMessage()
		if err != nil {
			return
		}
		liao := model.Liao{
			UserId:   int64(UserId),
			FriendId: int64(FriendId),
			Text:     string(data),
		}

		err = liao.LiaoAdd(config.DB)
		if err != nil {
			return
		}

		friendIdNode := Clients[friendId]
		friendIdNode.Data <- data
		rab.PublishSimple(string(data))
	}

}

func SendSmsNode(myNode *Node) {
	for {
		select {
		case data := <-myNode.Data:
			if err := myNode.conn.WriteMessage(websocket.TextMessage, data); err != nil {
				return
			}

		}
	}
}
